package www.dianbaozu.com.ui.chat.chat

import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import www.dianbaozu.com.R
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.data.repository.AppDataManager
import www.wen.com.common.lib.extension.getString

class ChatViewModel @ViewModelInject constructor(private val appDataManager: AppDataManager) :
    BaseViewModel() {

    @FlowPreview
    fun getUsersOnlineStatus(
        accids: Array<String>,
        action: ((Result.Success<List<UseInfoEntity>>) -> Unit)
    ) {
        viewModelScope.launch {
            appDataManager.requestUsersOnlineStatusFlow(accids)
                .retryWhen { cause, attempt ->
                    return@retryWhen cause.message == "网络异常" && attempt <= 1
                }
                .catch { cause ->
                    loading.value = UiStateCustom(
                        stateData = LoadingDialog(
                            tip = cause.message ?: "获取好友在线状态失败",
                            loadingDialogStateType = LoadingDialogStateType.ERROR,
                            isShowDialogTip = false,
                            isShowToastTip = true
                        )
                    )
                }
                .collect {
                    action.invoke(it)
                    //每30秒获取一次在线状态
                    delay(30000)
                    if (!accids.isNullOrEmpty()) {
                        getUsersOnlineStatus(accids, action)
                    }
                }
        }
    }

}